<?php

namespace app\models;

use think\Db;
use think\Model;

class User extends Model
{
    protected $pk = 'id';
    protected $autoWriteTimestamp = 'datetime';
    protected $createTime = 'created';
    protected $defaultSoftDelete = 0;

    /**
     * 资产变动变更记录
     * @param $user_id   // 用户
     * @param $comeuser_id   // 来源ID
     * @param $before   // 变化前资产信息
     * @param $money   // 变化金额
     * @param $cointype   // 币种类型
     * @param $handfee   // 手续费
     * @param $type   // 变化类型
     * @param $info   //备注
     * @param $source   // 资产来源ID
     * @return void
     */
    public static function MoneyEdit($user, $atype = 0, $type = 0, $money = 0, $info = '', $source = 0, $handfee, $comeuser_id = 0)
    {
        switch ($atype) {
            case '1':
                $name = 'umoney';
                break;
            case '2':
                $name = 'pmoney';
                break;
            case '3':
                $name = 'tmoney';
                break;
            default:
                throw new \Exception("资产类型错误，请重试", 100);
                break;
        }
        if ($money != 0) {
            if ($money < 0 && $user[$name] < $money) {
                throw new \Exception("资产不足，请重试", 100);
            }
            $res = (new User())->where(['id' => $user['id'], $name => $user[$name]])->setInc($name, $money);
            if (!$res) {
                throw new \Exception("资产修改失败，请重试", 100);
            }
            $res2 = (new MoneyLog())->save([
                'timeid' => time(),
                'user_id' => $user['id'],
                'atype' => $atype,
                'comeuser_id' => $comeuser_id,
                'befores' => $user[$name],
                'money' => $money,
                'after' => ($user[$name] + $money),
                'type' => $type,
                'info' => $info,
                'source' => $source,
                'handfee' => $handfee
            ]);
            if (!$res2) {
                throw new \Exception("资产记录失败，请重试", 100);
            }
        }
        if ($atype == 3) {
            $level = (new UserConfig())->order('level desc')->where('pnumber', '<=', $user['tmoney'])->value('level') ?? 0;
            if ($level >= 1 && $user['level'] != $level && $user['level'] > 0) {
                User::where('id', $user['id'])->update(['level' => $level]);
            }
        }
    }
}
